package com.ls.io.rpc.transport;

import com.alibaba.fastjson.JSON;
import com.ls.io.rpc.protobuf.RpcHeader;
import com.ls.io.rpc.protobuf.RpcPackage;
import com.ls.io.rpc.utils.SeriUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/9 11:00
 * @since
 */
public class RpcMessageEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        RpcPackage pck = (RpcPackage)msg;
        RpcHeader header = pck.getHeader();

        byte[] body = SeriUtils.seriable(pck.getContent());
        header.setLength(body.length);

        out.writeBytes(header.toArray());
        out.writeBytes(body);

        System.out.println(String.format("send header: %s, content: %s", JSON.toJSONString(header), new String(body, "utf-8")));
    }
}
